package com.lwx.sys.utils;

import com.lwx.sys.constant.Constant;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class FileUpLoadAndDownUtil {

    private static SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");

    //获取当前时间
    public static String getDirNameByCurrentDate(){

        return simpleDateFormat.format(new Date());

    }

    //根据老文件名生成新文件名
    public static String getNewFileNameUseUUID(String oldName){
        //得到 . 后面的后缀（文件类型）
        String end = oldName.substring(oldName.lastIndexOf("."));

        return UUID.randomUUID().toString().replace("-","").toUpperCase()+end;

    }


    public static ResponseEntity<Object> showImage(String uploadRootPath, String filePath) {
        File file = new File(uploadRootPath, filePath);
        if (file.exists()){
            //把图片放到byte[]
            byte[]  bytes = null;
            try {
                //读取文件，转化成字节数组
                bytes=FileUtils.readFileToByteArray(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //创建相应头
            HttpHeaders header = new HttpHeaders();
            //设置相应内容的类型
            header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //设置附件名称
            header.setContentDispositionFormData("attachment",file.getName());
            //创建 ResponseEntity 对象

            ResponseEntity<Object> responseEntity = new ResponseEntity<>(bytes, header, HttpStatus.CREATED);

            return responseEntity;
        }else {
            return null;
        }

    }

    //改名
    public static String changeFileName(String uploadRootPath, String imgpath) {

        String path = imgpath.replace("_temp", "");

        File file = new File(uploadRootPath, imgpath);
        File file1 = new File(uploadRootPath, path);

        file.renameTo(file1);

        return path;


    }

    public static void deleteFile(String uploadRootPath, String imgpath) {

        //如果不是缺省（默认）图片
        if (!imgpath.equals(Constant.USER_DEFAULT_IMAGE)) {
            File file = new File(uploadRootPath, imgpath);
            if (file.exists()){
                file.delete();
            }

        }


    }
}
